package classpath

import "path/filepath"

type Classpath struct {
	BootClassPath_ Entry // 启动类加载器
	ExtClassPath_  Entry // 拓展类加载器
	AppClassPath_  Entry // 应用类加载器
}

func (self *Classpath) parseBootAndExtClasspath(jreOption string) {
	jreLibPath := filepath.Join(jreOption, "lib", "*")
	self.BootClassPath_ = NewWildcardEntry(jreLibPath)
	jreExtPath := filepath.Join(jreOption, "lib", "ext", "*")
	self.ExtClassPath_ = NewWildcardEntry(jreExtPath)
}

func (c *Classpath) ReadClass(className string) ([]byte, Entry, error) {
	className = className + ".class"
	if data, entry, err := c.BootClassPath_.ReadClass(className); err == nil {
		return data, entry, err
	}
	if data, entry, err := c.ExtClassPath_.ReadClass(className); err == nil {
		return data, entry, err
	}
	return c.AppClassPath_.ReadClass(className)
}

func (self *Classpath) parseAppClasspath(cpOption string) {
	if cpOption == "" {
		cpOption = "."
	}
	self.AppClassPath_ = NewEntry(cpOption)
}

func Parse(jreOption string, cpOption string) *Classpath {
	cp := &Classpath{}
	//解析启动类和扩展类路径
	cp.parseBootAndExtClasspath(jreOption)
	//解析应用类路径
	cp.parseAppClasspath(cpOption)
	return cp
}
